# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: InstGenSS_L8164B.py
  @time: 2022/2/22 14:39
  @desc:
"""
import time

from ATS.instrumentDriver import InstGen
import math
from utils.singleton_util import singleton


@singleton
class SS_L8164B(InstGen.SS):
    def __init__(self, name):
        super().__init__(name)

    def idn(self):
        return self.handler.ask("*IDN?")

    def set_wave_length(self, wave_length):
        self.handler.write(f"sour0:wav {wave_length}NM")

    def set_power_unit(self, unit):
        """
        设置8164的power的单位
        :param unit:0 dbm,1 w
        :return:
        """
        self.handler.write(f"sour0:pow:unit {unit}")

    def set_power(self, power_value):
        """
        设置power的value
        :param power_value:
        :return:
        """
        self.handler.write(f"sour0:pow {power_value} dbm")

    def cls(self):
        self.handler.write("*cls")

    def reset(self):
        self.handler.write("*RST")

    def trigger_config(self, config=1):
        """
        Sets the hardware trigger configuration with regard to Output and Input Trigger Connectors.
        :param config: 0 or DISabled/1 or DEFault/2 or PASSthrough/3 or LOOPback
        :return:
        """
        self.handler.write(f"trig:conf {config}")

    def set_start_stop_step_wave(self, start_wave, stop_wave, step_wave):
        """设置开始、结束波长和波长的步进
        :param start_wave:开始波长
        :param stop_wave:结束波长
        :param step_wave:波长步进
        """
        self.handler.write(f"WAVelength:SWEep:STARt {start_wave}NM")
        self.handler.write(f"WAVelength:SWEep:STOP {stop_wave}NM")
        self.handler.write(f"WAVelength:SWEep:STEP {step_wave}NM")

    def stop_sweep(self):
        self.handler.write("wav:swe STOP")

    def set_wave_sweep_speed(self, speed: float = 100):
        """
        设置波长扫描速度 Speed as a float value in meters per second (m/s). wav:swe:spe 10nm/s
        :param speed:
        :return:
        """
        self.handler.write(f"wav:swe:spe {speed}nm/s")

    def set_repeat_mode(self, repeat_mode="ONEW"):
        """
        设置重复模式
        :param repeat_mode:ONEWay/TWOWay
        :return:
        """
        self.handler.write(f"wav:swe:rep {repeat_mode}")

    def set_sweep_mode(self, sweep_mode="CONT"):
        """
        Sets the sweep mode.
        :param sweep_mode: STEPped/MANual/CONTinuous
        :return:
        """
        self.handler.write(f"WAVelength:SWEep:MODE {sweep_mode}")

    def query_sweep_pmax(self, start_wavelength: float, stop_wavelength: float):
        """
        Returns the power to the highest permissible power for the selected wavelength sweep
        :param start_wavelength:
        :param stop_wavelength:
        :return:
        """
        w_result = self.handler.ask(f"WAVelength:SWEep:PMAX? {start_wavelength}nm,{stop_wavelength}nm")
        dbm_result = math.log10(float(w_result) * 1000) * 10
        return dbm_result

    def set_wave_sweep_state(self, state):
        """
        :param state: STOP|0|STARt|1|PAUSe|2|CONTinue|3
        :return:
        """
        # 开始扫描触发和终止扫描触发
        self.handler.write(f"wav:swe {state}")

    def trigger_output(self, output="STF"):
        # 触发输出，每个波长输出一个触发信号：
        """
        Specifies when an output trigger is generated and arms the module.
        DISabled:
        AVGover:
        MEASure:
        MODulation:
        STFinished:
        SWFinished:
        SWSTarted:
        Never.
        :return:
        """
        self.handler.write(f":TRIGger:OUTPut {output}")

    def get_sweep_status(self):
        # :source0:wav:swe:state？
        return self.handler.ask(f":source0:wav:swe:state?")

    def trigger(self,state=1):
        self.handler.write(f":TRIGger {state}")

    def trigger_input(self, trigger_response="SWS"):
        """
           Sets the incoming trigger response and arms the module.
           IGNore:Ignore incoming trigger.
           SMEasure:Start a single measurement. If a measurement function is active, see
                   :SENSe[n][:CHANnel[m]]:FUNCtion:STATe on page 104, one sample is performed and
                   the result is stored in the data array, see :SENSe[n][:CHANnel[m]]:FUNCtion:RESult?
                   on page 100.
           CMEasure:Start a complete measurement. If a measurement function is active,
                   see:SENSe[n][:CHANnel[m]]:FUNCtion:STATe on page 104, a complete measurement
                   function is performed.
           NEXTstep:Perform next step of a stepped sweep.
           SWStart:Start a sweep cycle.
           :param trigger_response:
           :return:
           """
        self.handler.write(f":TRIGger:INPut {trigger_response}")

    def output_on(self):
        """
        打开光输出
        :return:
        """
        state = int(self.handler.ask(f":OUTPUT:CHANNEL:STATE?"))  # on off
        if not state:
            self.handler.write(f":OUTPUT:CHANNEL:STATE 1")  # on
            state = int(self.handler.ask(f":OUTPUT:CHANNEL:STATE?"))  # on off

    def output_off(self):
        """
        关闭光输出
        :return:
        """
        state = int(self.handler.ask(f":OUTPUT:CHANNEL:STATE?"))  # on off
        if state:
            self.handler.write(f":OUTPUT:CHANNEL:STATE 0")  # on off

    def fetch_power_value(self):
        self.set_power_unit(0)
        input_power = self.handler.ask("sour0:pow?")
        return input_power

    def get_source_wavelength(self):
        wavelength = self.handler.ask("sour0:wav?")
        return wavelength

    # def _change_c_switch(self):
    #     self.handler.write(f"rout3:chan1 A,3")  # 切开关
    #
    # def _change_o_switch(self):
    #     self.handler.write(f"rout3:chan1 A,1")  # 切开关

    # def __monitor_error(self):
    #     result = self.handler.ask("SYST:ERR?")
    #     return result

    # def __del__(self):
    #     self.output_off()
